Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The bn.js package is a library that provides support for arbitrary-precision arithmetic operations on big numbers in JavaScript. It is commonly used in cryptography, financial calculations, and anywhere precise arithmetic with large integers is required.
Big Number Arithmetic
Performing basic arithmetic operations such as addition, subtraction, multiplication, division, and modulo on big numbers.
const BN = require('bn.js');
let a = new BN('123456789');
let b = new BN('987654321');
let sum = a.add(b); // Addition
let diff = a.sub(b); // Subtraction
let product = a.mul(b); // Multiplication
let quotient = a.div(b); // Division
let remainder = a.mod(b); // Modulo
Comparison Operations
Comparing big numbers to determine if they are equal, less than, or greater than each other.
const BN = require('bn.js');
let a = new BN('12345');
let b = new BN('12345');
let c = new BN('54321');
a.eq(b); // true, a equals b
a.lt(c); // true, a is less than c
a.gt(c); // false, a is not greater than c
Bitwise Operations
Performing bitwise operations such as AND, OR, XOR, and NOT on big numbers.
const BN = require('bn.js');
let a = new BN('1011', 2);
let b = new BN('1101', 2);
let and = a.and(b); // AND operation
let or = a.or(b); // OR operation
let xor = a.xor(b); // XOR operation
let not = a.not(); // NOT operation
Reduction Contexts
Using reduction contexts to perform modular arithmetic efficiently, particularly useful in modular exponentiation and cryptographic operations.
const BN = require('bn.js');
let p = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16);
let a = new BN('7fffffffffffffffffffffff7ffffe17ff', 16);
let red = BN.red(p);
let b = a.toRed(red); // Convert to Montgomery representation
let c = b.redSqr().redMul(b); // Perform operations in reduction context
let d = c.fromRed(); // Convert out of Montgomery representation
big.js is a small, fast JavaScript library for arbitrary-precision decimal arithmetic. It focuses on decimal numbers and provides a simpler API but does not support bitwise operations like bn.js.
bignumber.js is another arbitrary-precision arithmetic library for JavaScript and Node.js. It supports decimal and non-decimal arithmetic and has a more extensive API than bn.js, but it might be slower for some operations due to its focus on decimal precision.
decimal.js is a library for arbitrary-precision decimal arithmetic. It is similar to bignumber.js in its focus on decimal numbers and provides a comprehensive set of features for decimal arithmetic, but it does not provide the same level of support for non-decimal and bitwise operations as bn.js.
BigNum in pure javascript
npm install --save bn.js
const BN = require('bn.js');
var a = new BN('dead', 16);
var b = new BN('101010', 2);
var res = a.add(b);
console.log(res.toString(10)); // 57047
There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name:
i
- perform operation in-place, storing the result in the host object (on
which the method was invoked). Might be used to avoid number allocation costsu
- unsigned, ignore the sign of operands when performing operation, or
always return positive value. Second case applies to reduction operations
like mod()
. In such cases if the result will be negative - modulo will be
added to the result to make it positiveThe only available postfix at the moment is:
n
- which means that the argument of the function must be a plain JavaScript
numbera.iadd(b)
- perform addition on a
and b
, storing the result in a
a.pmod(b)
- reduce a
modulo b
, returning positive valuea.iushln(13)
- shift bits of a
left by 13Prefixes/postfixes are put in parens at the of the line. endian
- could be
either le
(little-endian) or be
(big-endian).
a.clone()
- clone numbera.toArray(endian, length)
- convert to byte array, and optionally zero
pad to length, throwing if already exceedinga.toString(base, padding)
- convert to base-string and pad with zeroesa.bitLength()
- get number of bits occupieda.zeroBits()
- return number of less-significant consequent zero bits
(example: 1010000
has 4 zero bits)a.byteLength()
- return number of bytes occupieda.isEven()
- no commentsa.isOdd()
- no commentsa.cmp(b)
- compare numbers and return -1
(<
), 0
(==
), or 1
(>
)
depending on the comparison result (ucmp
, cmpn
)a.neg()
- negate sign (i
)a.abs()
- absolute value (i
)a.add(b)
- addition (i
, n
)a.sub(b)
- subtraction (i
, n
)a.mul(b)
- multiply (i
, n
)a.sqr()
- square (i
)a.pow(b)
- raise a
to the power of b
a.div(b)
- divide (divn
, idivn
)a.mod(b)
- reduct (u
, n
)a.divRound(b)
- rounded divisiona.or(b)
- or (i
, u
)a.and(b)
- and (i
, u
, andln
) (NOTE: andln
is going to be replaced
with andn
in future)a.xor(b)
- xor (i
, u
)a.setn(b)
- set specified bit to 1
a.shln(b)
- shift left (i
, u
)a.shrn(b)
- shift right (i
, u
)a.testn(b)
- test if specified bit is seta.maskn(b)
- clear bits with indexes higher or equal to b
(i
)a.bincn(b)
- add 1 << b
to the numbera.gcd(b)
- GCDa.egcd(b)
- Extended GCD results ({ a: ..., b: ..., gcd: ... }
)a.invm(b)
- inverse a
modulo b
When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like Montgomery multiplication, or using special algorithm for Mersenne Prime.
To enable this tricks one should create a reduction context:
var red = BN.red(num);
where num
is just a BN instance.
Or:
var red = BN.red(primeName);
Where primeName
is either of these Mersenne Primes:
'k256'
'p224'
'p192'
'p25519'
Or:
var red = BN.mont(num);
To reduce numbers with Montgomery trick. .mont()
is generally faster than
.red(num)
, but slower than BN.red(primeName)
.
Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should:
Here is how one may convert numbers to red
:
var redA = a.toRed(red);
Where red
is a reduction context created using instructions above
Here is how to convert them back:
var a = redA.fromRed();
Most of the instructions from the very start of this readme have their counterparts in red context:
a.redAdd(b)
, a.redIAdd(b)
a.redSub(b)
, a.redISub(b)
a.redShl(num)
a.redMul(b)
, a.redIMul(b)
a.redSqr()
, a.redISqr()
a.redSqrt()
- square root modulo reduction context's primea.redInvm()
- modular inverse of the numbera.redNeg()
a.redPow(b)
- modular exponentiationThis software is licensed under the MIT License.
Copyright Fedor Indutny, 2015.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Big number implementation in pure javascript
The npm package bn.js receives a total of 32,774,672 weekly downloads. As such, bn.js popularity was classified as popular.
We found that bn.js demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.